#include <fcntl.h>


#include <unistd.h>

#include <stdio.h>
#include <cstring>
#include <termios.h>

#include <stdlib.h>

int open_serial_port(const char *device);

void configure_serial_port(int fd, int baud_rate);

ssize_t read_from_serial_port(int fd, void *buf, size_t nbytes);

void close_serial_port(int fd);

void write_from_serial_port(char* writebuf,int fd);

int main() {

    const char *device = "/dev/ttyUSB2";

    int baud_rate = B9600;

    int fd = open_serial_port(device);

    if (fd == -1) {

        return 1;

    }

    configure_serial_port(fd, baud_rate);

    char buffer[256];

    ssize_t n = read_from_serial_port(fd, buffer, sizeof(buffer));

    if (n > 0) {

        buffer[n] ;

        printf("Read %zd bytes: %sn", n, buffer);
        
        
	   


    } else {

        printf("No data read from serial portn");

    }
    
	char writebuf[]="HELLO!!!";

    // 	write(fd,writebuf, strlen(writebuf));

    write_from_serial_port(writebuf, fd);    

    close_serial_port(fd);

    return 0;

}

void write_from_serial_port(char* writebuf,int fd){
    int st=write(fd,writebuf, strlen(writebuf)); 
}

int open_serial_port(const char *device) {

    int fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY);

    if (fd == -1) {

        perror("Unable to open serial port");

    } else {

        fcntl(fd, F_SETFL, 0);

    }

    return fd;

}



void configure_serial_port(int fd, int baud_rate) {

    struct termios options;

    tcgetattr(fd, &options);

    cfsetispeed(&options, baud_rate);

    cfsetospeed(&options, baud_rate);

    options.c_cflag |= (CLOCAL | CREAD);

    options.c_cflag &= ~PARENB;

    options.c_cflag &= ~CSTOPB;

    options.c_cflag &= ~CSIZE;

    options.c_cflag |= CS8;

    tcsetattr(fd, TCSANOW, &options);

}

ssize_t read_from_serial_port(int fd, void *buf, size_t nbytes) {

    return read(fd, buf, nbytes);

}

void close_serial_port(int fd) {

    close(fd);

}
